package lv.rtu.ditf.dc.fs;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;

/**
 * 
 * @author Pāvels Koliškins, Edgars Matisāns
 *
 */
public class SerializationUtil {

    public static void serializeHashMap(HashMap<String, Integer> hashMap, File file) throws IOException {
        ObjectOutputStream objectOutputStream = null;
        try {
            objectOutputStream = new ObjectOutputStream(new FileOutputStream(file));
            objectOutputStream.writeObject(hashMap);
            objectOutputStream.flush();
            objectOutputStream.close();
        } 
        catch (IOException ex) {
            ex.printStackTrace();
            throw ex;
        } finally {
            try {
                objectOutputStream.close();
            } catch (IOException ex) {
                ex.printStackTrace();
                throw ex;
            }
        }
    }

    @SuppressWarnings("unchecked")
    public static HashMap<String, Integer> deserializeHashMap(File file) throws ClassNotFoundException, IOException {
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(file));
            HashMap<String, Integer> hashMap = (HashMap<String, Integer>) objectInputStream.readObject();
            return hashMap;
        } catch (IOException ex) {
            ex.printStackTrace();
            throw ex;
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
            throw ex;
        }
    }
}